(function($) {
    $.jTimeTable = function() {
        var xmlDoc;
        var inner;
        var $inner;
        var arrData;

        var jtt = {

            xmlFileName: function(busVal, dirVal) {

                var xmlfn;

                if (busVal == "mazul"){
                    switch(dirVal){
                        case "rosvc":
                            xmlfn = "m_azul_ros_vc.xml";
                            break;
                        case "vcros":
                            xmlfn = "m_azul_vc_ros.xml";
                            break;
                    }
                }
                else {
                    return null;
                }

                return xmlfn;

            },

            stopsName: function(val) {

                var name;
                switch(val){
                    case "t_ros": name="Terminal de Rosario"; break;
                    case "esp_sj": name="España y San Juan"; break;
                    case "esp_pel": name="España y Pellegrini"; break;
                    case "oro_seg": name="Oroño y Segui"; break;
                    case "oro_cir": name="Oroño y Circunvalación"; break;
                    case "arroyo": name="Arroyo Seco (Estación ESSO)"; break;
                    case "fighiera": name="Fighiera"; break;
                    case "pavon": name="Pavón"; break;
                    case "empalme": name="Empalme"; break;
                    case "villa": name="Villa Constitución"; break;
                    case "roc_sj": name="Presidente Roca y San Juan"; break;
                    case "roc_pel": name="Presidente Roca y Pellegrini"; break;
                    default: name=val;
                }

                return name;

            },

            isHoliday: function(d,m,y) {

                var holidays=[[13,10,2014],[24,11,2014],[8,12,2014],[25,12,2014],[26,12,2014],
                              [1,1,2015],[16,2,2015],[17,2,2015],[23,3,2015],[24,3,2015],
                              [2,4,2015],[3,4,2015],[1,5,2015],[25,5,2015],[20,6,2015],[9,7,2015],
                              [17,8,2015],[12,10,2015],[23,11,2015],[7,12,2015],[8,12,2015],[25,12,2015]
                             ];

                for (var i=0;i < holidays.length; i++)
                    if (d===holidays[i][0] && m===holidays[i][1] && y===holidays[i][2])
                        return true;

                return false;

            },

            dayNumberToTableValue: function(dat) {

                var dn = dat.getDay();
                var d = dat.getDate();
                var m = dat.getMonth()+1;
                var y = dat.getFullYear();

                if (this.isHoliday(d,m,y)) return "feriado";

                switch (dn){
                    case 0: return "domingo";
                    case 6: return "sabado";
                    default: return "lunvie";
                }

            },

            diff: function(d1,d2) {

                var h1,h2, m1, m2, d;
                var ms1, ms2;

                h1 = parseInt(d1.split(":")[0]);
                h2 = parseInt(d2.split(":")[0]);
                m1 = parseInt(d1.split(":")[1]);
                m2 = parseInt(d2.split(":")[1]);
                ms1 = h1*60 + m1;
                ms2 = h2*60 + m2;

                return (ms1 - ms2);

            },

            loadXMLDoc: function(filename) {

                if (window.XMLHttpRequest)
                      {
                            xhttp=new XMLHttpRequest();
                              }
                else // code for IE5 and IE6
                      {
                            xhttp=new ActiveXObject("Microsoft.XMLHTTP");
                              }
                xhttp.open("GET",filename,false);
                xhttp.send();

                return xhttp.responseXML;

            },

            fillStops: function(arr) {

                var stVal;

                $("#stop").empty();

                for (var i=0; i < arr.length; i++){
                    stVal = arr[i].nodeName;
                    $("#stop").append("<option value='"+stVal+"'>"+this.stopsName(stVal)+"</option>");
                }

            },

            loadArray: function() {

                var $row;
                var nodeName, nodeValue;
                var arr = new Array();

                for(var i=0; i < $inner.length; i++){
                    $row = $($inner[i].childNodes);
                    arr[i] = {};
                    for(var j=0; j < $row.length; j++){
                        nodeName = $row[j].nodeName;
                        if ($row[j].firstChild != null)
                            nodeValue = $row[j].firstChild.nodeValue;
                        arr[i][nodeName] = nodeValue;
                    }
                }

                return arr;

            },

            loadData: function() {

                var busVal, dirVal;
                busVal = $("#bus").find(":selected").attr("value");
                dirVal = $("#dir").find(":selected").attr("value");

                var xml = this.xmlFileName(busVal, dirVal);

                if (xml === null) return -1;

                xmlDoc = this.loadXMLDoc(xml);
                inner = xmlDoc.documentElement.childNodes;
                $inner = $(inner);
                arrData = this.loadArray();

                var $first = $(inner[0].childNodes);
                this.fillStops($first.splice(2, $first.length));

                return 0;

            },

            date: function() {

                var y,m,d,hr,min, date, aux;

                y = $("#year").val();
                m = $("#month").val() - 1;
                d = $("#day").val();
                hr = $("#hours").val();
                min = $("#minutes").val();

                if (y && m && d && hr && min){
                    date = new Date(y,m,d,hr,min);
                }
                else if (y && m && d){
                    aux = new Date();
                    date = new Date(y,m,d,aux.getHours(), aux.getMinutes());
                }
                else if (hr && min){
                    aux = new Date();
                    date = new Date(aux.getFullYear(),aux.getMonth(),aux.getDay(),hr, min);
                }
                else{
                    date = new Date();
                }

                return date;

            },

            when: function() {

                var i,j = 0;
                var today = this.date();
                console.log(today);
                var day = this.dayNumberToTableValue(today);
                var tNow = today.getHours() + ":" + today.getMinutes();
                var prev = -1, next = -1, sndNext = -1;
                var tAtStop;

                var stop = $("#stop").find(":selected").attr("value");

                for(i = 0; i < $inner.length; i++){

                    if (arrData[i]['dia'] === day){

                        if (j != 0) prev = Math.abs(next);
                        tAtStop = arrData[i][stop];
                        next = this.diff(tAtStop, tNow);
                        j = 1;

                        if (next >= 0){

                            while (i+j < $inner.length && arrData[i+j]['dia'] != day) j++;

                            if (i+j < $inner.length){
                                tAtStop = arrData[i+j][stop];
                                sndNext = this.diff(tAtStop, tNow);
                            }

                            break;
                        }
                    }
                }

                if (next >= 0)
                    $("#next").text("El próximo pasará en "+ next + " minutos");
                else{
                    $("#next").text("No más coles por hoy");
                    prev = Math.abs(next);
                }

                if (prev > 0)
                    $("#previous").text("El último pasó hace "+ prev + " minutos\n");
                else
                    $("#previous").text("");

                if (sndNext > 0)
                    $("#sndNext").text("El ooootro pasará en "+ sndNext + " minutos\n");
                else
                    $("#sndNext").text("");



            },

            showError: function() {

                $("#err").text("Error en la base de datos");

            },

            clearError: function() {

                $("#err").text("");

            },

            addHTMLElements: function() {

                $("#answers").append("<label id='previous'></label><br><br>");
                $("#answers").append("<label id='next'></label><br><br>");
                $("#answers").append("<label id='sndNext'></label><br><br>");
                $("#answers").append("<label id='err' style='color:red' ></label>");


            }
        };

        return {

            init: function() {
                if (jtt.loadData() < 0)
                    jtt.showError();
                else
                    jtt.clearError();

                jtt.addHTMLElements();

            },

            when: function() {
                jtt.when();
            },

            refresh: function() {
                if (jtt.loadData() < 0)
                    jtt.showError();
                else
                    jtt.clearError();
            }

        };
    };

})(jQuery);
